import {defineStore} from 'pinia'
import {ref} from "vue";
import {getUserInfo, login} from "@/api/user.js";
import router from "@/router/index.js"
import {useRouteStore} from "@/pinia/index.js";

export const useUserStore = defineStore('user', () => {
    const userInfo = ref({
        uuid: '',
        username: '',
        headerImg: '',
        authority: {},
        sideMode: 'dark',
        activeColor: '#4D70FF',
        baseColor: '#fff'
    })
    const token = ref("")

    async function loginIn(loginInfo) {
        const res = await login(loginInfo)
        if (res.code === 200) {
            userInfo.value = res.data.user
            token.value = res.data.token
            try {
                const routeStore = useRouteStore();
                await routeStore.SetAsyncRouter()
                const asyncRouters = routeStore.asyncRouters
                asyncRouters.forEach(asyncRouter => {
                    router.addRoute(asyncRouter)
                })
                router.push({name: userInfo.value.authority.defaultRouter})
                return true
            } catch (err) {
                return false
            }
        }
    }

    function logout() {
        token.value = ""
        sessionStorage.clear()
        router.push({name: 'login', replace: true})
        window.location.reload()
    }

    async function GetUserInfo() {
        const res = await getUserInfo()
        if (res.code === 200) {
            userInfo.value = res.data.userInfo
        }
        return res
    }

    return {
        userInfo,
        token,
        loginIn,
        logout,
        GetUserInfo
    }
}, {persist: true})
